---
title: Replication Code for "In Party We Trust? Voter Support for Party-Backed Candidates in Primary Elections" 
header-includes:
   - \usepackage{dcolumn}
   - \usepackage{caption}
output: 
  pdf_document:
    toc: true
    toc_depth: 3
  

---

# Overview 


# Setup

```{r setup,results="hide",warning=F,message=FALSE}
# Set Working Directory
wd <- "." # Replace with file path to replication files
setwd(wd)
# Libraries
# Load packages
library(tidyverse)
library(ggpubr)
library(kableExtra)
library(haven)
library(cjoint)
library(rgeolocate)
library(foreign)
library(dplyr)
library(ggeffects)
library(knitr)
library(sjPlot)
library(sjmisc)
library(sjlabelled)
library(stargazer)
library(utils)
library(psych)
library(gridExtra)
library(grDevices)
library(memisc)
library(readr)
library(texreg)
library(patchwork)
library(lmtest)
library(car)
library(FindIt)
library(estimatr)

# Options
options(digits=4,width=100,scipen=8,warn=-1,knitr.table.format = "latex")
opts_chunk$set(eval=T,echo=T
               ,message=F,warning=F,cache=T,
               fig.width = 8,
               fig.path = "00_figures/",results = "hide"
               )


# Load data
load("mturk_wide_clean_data.rda")
load("mturk_long_clean_data.rda")
load("qualtrics_clean_data.rda")
load("nes.rda")

# Subset Data
# Split Dems and Reps into separate data frames
dem_df<- dfc[dfc$pid_dem_all==1,]
rep_df<- dfc[dfc$pid_rep_all==1,]
dem_df_q<- df_q[df_q$party_dem==1,]
rep_df_q<- df_q[df_q$party_rep==1,]

# Set up Data 
# Set levels
dem_df$cand_age =factor(dem_df$cand_age, 
                        levels = c("37","46","52","60","68","75")
                        )
dem_df$cand_gender =factor(dem_df$cand_gender, levels = c("Male","Female"))
dem_df$cand_race =factor(dem_df$cand_race, 
                         levels = c("White", "African American", 
                                    "Hispanic", "Asian American")
                         )
dem_df$cand_occup =factor(dem_df$cand_occup, 
                          levels = c("Businessperson", "Teacher", "Doctor", 
                                     "Lawyer","Military officer")
                          )
dem_df$cand_exp =factor(dem_df$cand_exp, 
                        levels = c("None", "Mayor","City Council", "State Senator")
                        )
dem_df$cand_ideo =factor(dem_df$cand_ideo, 
                         levels = c("6", "7", "8", "9")
                         )
dem_df$cand_endorse =factor(dem_df$cand_endorse, 
                            levels = c("NoEndorsements", "Demstate", "Demloc",
                                       "Sanders","Obama", "Pelosi","DCCC")
                            )
rep_df$cand_age = factor(rep_df$cand_age, 
                         levels = c("37","46","52","60","68","75")
                         )
rep_df$cand_gender = factor(rep_df$cand_gender, 
                            levels = c("Male","Female")
                            )
rep_df$cand_race = factor(rep_df$cand_race, 
                          levels = c("White", "African American", 
                                     "Hispanic", "Asian American")
                          )
rep_df$cand_occup = factor(rep_df$cand_occup, 
                           levels = c("Businessperson", "Teacher", "Doctor", 
                                      "Lawyer","Military officer")
                           )
rep_df$cand_exp = factor(rep_df$cand_exp, 
                         levels = c("None", "Mayor","City Council", "State Senator")
                         )
rep_df$cand_ideo = factor(rep_df$cand_ideo, 
                          levels = c("6", "7", "8", "9")
                          )
rep_df$cand_endorse = factor(rep_df$cand_endorse, 
                             levels = c("NoEndorsements", "Repstate", "Reploc",
                                        "Cruz","Trump", "McConnell","NRCC")
                             )

# Create Nice Names 

dem_df$`Candidate Endorsements` <- dem_df$cand_endorse
dem_df$`Candidate Experience` <- dem_df$cand_exp
dem_df$`Candidate Ideology` <- dem_df$cand_ideo
dem_df$`Candidate Age` <- dem_df$cand_age
dem_df$`Candidate Gender` <- dem_df$cand_gender
dem_df$`Candidate Race` <- dem_df$cand_race
dem_df$`Candidate Occupation` <-  dem_df$cand_occup



rep_df$`Candidate Endorsements` <- rep_df$cand_endorse
rep_df$`Candidate Experience` <- rep_df$cand_exp
rep_df$`Candidate Ideology` <- rep_df$cand_ideo
rep_df$`Candidate Age` <- rep_df$cand_age
rep_df$`Candidate Gender` <- rep_df$cand_gender
rep_df$`Candidate Race` <- rep_df$cand_race
rep_df$`Candidate Occupation` <-  rep_df$cand_occup

# Attributes

att_dem <- list(
  `Candidate Age`	=c("37","46","52","60","68","75"),
  `Candidate Gender`	=c("Male","Female"),
  `Candidate Race`	=c("White","African American","Hispanic","AsianAmerican"),
  `Candidate Occupation` = c("Businessperson","Teacher","Doctor",
                           "Lawyer","Militaryofficer"),
  `Candidate Experience` = c("None","CityCouncil","Mayor","StateSenator"),
  `Candidate Ideology` = c("6","7","8","9"),
  `Candidate Endorsements`=c("NoEndorsements","Demstate","Demloc",
                             "Sanders","Obama","Pelosi","DCCC")
)

att_rep <- list(
  `Candidate Age` = c("37","46","52","60","68","75"),
  `Candidate Gender` = c("Male","Female"),
  `Candidate Race` = c("White", "AfricanAmerican", "Hispanic", "AsianAmerican"),
  `Candidate Occupation` = c("Businessperson", "Teacher", "Doctor",
                              "Lawyer","Militaryofficer"),
  `Candidate Experience` =c("None","City Council","Mayor","State Senator"),
  `Candidate Ideology` = c("6", "7", "8", "9"),
  `Candidate Endorsements` = c("NoEndorsements", "Repstate", "Reploc",
                               "Cruz","Trump", "McConnell","NRCC")
               )


constraint_list <- list()#No constraints

#Only weight adding here is for candidate race
mw_dem <- list()
mw_dem[["Candidate Age"]]<- rep(1/length(att_dem[["Candidate Age"]]),
                                              length(att_dem[["Candidate Age"]])
                                )
mw_dem[["Candidate Gender"]]<- rep(1/length(att_dem[["Candidate Gender"]]),
                                                 length(att_dem[["Candidate Gender"]])
                                   )
mw_dem[["Candidate Race"]] <- c(60/100, 15/100, 15/100, 10/100)

mw_dem[["Candidate Occupation"]]<- rep(1/length(att_dem[["Candidate Occupation"]]), 
                                                 length(att_dem[["Candidate Occupation"]])
                                       )
mw_dem[["Candidate Experience"]]<- rep(1/length(att_dem[["Candidate Experience"]]), 
                                                 length(att_dem[["Candidate Experience"]])
                                       )
mw_dem[["Candidate Ideology"]]<- rep(1/length(att_dem[["Candidate Ideology"]]), 
                                               length(att_dem[["Candidate Ideology"]])
                                     )
mw_dem[["Candidate Endorsements"]]<- rep(1/length(att_dem[["Candidate Endorsements"]]), 
                                                   length(att_dem[["Candidate Endorsements"]])
                                         )

mw_rep <- list()
mw_rep[["Candidate Age"]]<- rep(1/length(att_rep[["Candidate Age"]]),
                                length(att_rep[["Candidate Age"]])
                                )
mw_rep[["Candidate Gender"]]<- rep(1/length(att_rep[["Candidate Gender"]]),
                                   length(att_rep[["Candidate Gender"]])
                                   )
mw_rep[["Candidate Race"]] <- c(60/100, 15/100, 15/100, 10/100)

mw_rep[["Candidate Occupation"]]<- rep(1/length(att_rep[["Candidate Occupation"]]),
                                       length(att_rep[["Candidate Occupation"]])
                                       )
mw_rep[["Candidate Experience"]]<- rep(1/length(att_rep[["Candidate Experience"]]),
                                       length(att_rep[["Candidate Experience"]])
                                       )
mw_rep[["Candidate Ideology"]]<- rep(1/length(att_rep[["Candidate Ideology"]]),
                                     length(att_rep[["Candidate Ideology"]])
                                     )
mw_rep[["Candidate Endorsements"]]<- rep(1/length(att_rep[["Candidate Endorsements"]]),
                                         length(att_rep[["Candidate Endorsements"]])
                                         )


# Baselines
# set reference categories
baselines <- list()
baselines$cand_age <- "37"
baselines$cand_gender <- "Male"
baselines$cand_race <- "White"
baselines$cand_occup <- "Businessperson"
baselines$cand_exp <- "None"
baselines$cand_ideo <- "6"
baselines$cand_endorse <- "NoEndorsements"

# facet levels for interactions
facet.levels_trust<- list()
facet.levels_trust[["lowtrust"]]<- c("Low Trust")

facet.levels_trust_party <- list()
facet.levels_trust_party[["lowtrust_party"]] <- c("Low Trust")

facet.levels_trust_con <- list()
facet.levels_trust_con[["lowtrust_con"]] <- c("Low Trust")

facet.levels_tossup <- list()
facet.levels_tossup[["tossup"]] <- c(1)
facet.levels_lean <- list()
facet.levels_lean[["lean"]] <- c(1)
facet.levels_solid <- list()
facet.levels_solid[["solid"]] <- c(1)

# rename levels for plot
dem_levels<-list()
dem_levels[["Candidate Age"]]<-c("37","46","52","60","68","75")
dem_levels[["Candidate Gender"]]<-c("Male","Female")
dem_levels[["Candidate Race"]]<-c("White", "African American",
                                  "Hispanic", "Asian American")
dem_levels[["Candidate Occupation"]]<-c("Businessperson", "Teacher", "Doctor", 
                                        "Lawyer","Military")
dem_levels[["Candidate Experience"]]<-c("None","City Council" , 
                                        "Mayor", "State Senator")
dem_levels[["Candidate Ideology"]]<-c("6 (Moderate Liberal)", "7 (Solid Liberal)", 
                                      "8 (Solid Liberal)", "9 (Extremely Liberal")
dem_levels[["Candidate Endorsements"]]<-c("No Endorsements", "Democratic Town Committee",
                                          "State Democratic Party","Bernie Sanders",
                                          "Barack Obama", "Nancy Pelosi","DCCC")

rep_levels<-list()
rep_levels[["Candidate Age"]]<-c("37","46","52","60","68","75")
rep_levels[["Candidate Gender"]]<-c("Male","Female")
rep_levels[["Candidate Race"]]<-c("White", "African American", 
                                  "Hispanic", "Asian American")
rep_levels[["Candidate Occupation"]]<-c("Businessperson", "Teacher", 
                                        "Doctor", "Lawyer","Military")
rep_levels[["Candidate Experience"]]<-c("None","City Council" , 
                                        "Mayor", "State Senator")
rep_levels[["Candidate Ideology"]]<-c("6 (Moderate Conservative)", "7 (Solid Conservative)", 
                                      "8 (Solid Conservative)", "9 (Extremely Conservative")
rep_levels[["Candidate Endorsements"]]<-c("No Endorsements", "Republican Town Committee", 
                                          "State Republican Party","Ted Cruz",
                                          "Donald Trump", "Mitch McConnell","NRCC")




# Design

design_dem <- makeDesign(type = 'constraints', 
                         attribute.levels = att_dem, 
                         constraints = constraint_list,
                         level.probs = mw_rep
                         )


design_rep<- makeDesign(type = 'constraints', 
                        attribute.levels = att_rep,
                        constraints = constraint_list, 
                        level.probs = mw_rep)


```


# Functions


```{r functions}
# Update plot.amce() to return plot

plot_amce <- getAnywhere(plot.amce())$obj[[1]]
body(plot_amce) <- body(plot_amce) %>% 
  as.list %>% 
  append(quote(return(p))) %>% 
  as.call

# Wrap plot_amce to hide output of print(p) in plot.amce
plot_fn <- function(...)
  {
    png("temp.xyz")
    p <- plot_amce(...)
    dev.off()
    file.remove("temp.xyz")
    return(invisible(p))
}

# Get data function

get_data_fn <- function(...){
  p <- plot_fn(...)
  df <- invisible(p$data)
  return(df)
}


plot_interaction_fn <- function(the_data=dem_df,
                          the_model = NULL,
                          the_form = my_mod,
                          int = ~lowtrustf,
                          interaction_lab = "Trust in Institutions",
                          the_features = c("Candidate Endorsements", 
                                           "Candidate Experience",   
                                           "Candidate Ideology")){
  
  
m_amce <- get_data_fn(the_model, plot.display = "interaction")

#### Get Estimates of Marginal Means  
  
m_mm <- cregg::cj(the_data,
                      the_form,
                      id = ~resp_id,
                      level_order="descending",
                      by = int,
                      estimate = "mm")

#### Get Estimates of Difference in Marginal Means  

m_diff <- cregg::cj(the_data,
                        the_form,
                        id = ~resp_id,
                        level_order="descending",
                        by = int,
                        estimate = "mm_differences")

##### Format data for merging
df1 <- m_amce%>%
  fill(group,.direction="up")%>%
  mutate(
    pe = ifelse(pe >100,NA,pe),
    match = gsub("^*.* = ", "",facet),
    term = gsub("^*.* = ", "",facet),
    Type = "AMCE",
    printvar = factor(printvar, levels=rev(unique(printvar)))
  )%>%
  dplyr::select(printvar,group,pe,upper, lower, var,match,term,Type)


tmp <-  df1 %>% dplyr::select(var, match, printvar)

df2 <- tmp %>% left_join(
  m_mm %>%
    mutate(
      pe = estimate,
      var = gsub(" ","",paste(feature,level,sep="")),
      group = feature,
      Type = "Marginal Means",
      match = BY,
      term = BY,
    )%>%
    dplyr::select(group,pe,upper, lower, var,match,term,Type),
  by=c("var"="var","match"="match"))%>%
  fill(group,.direction="up")%>%
  fill(Type,.direction="up")%>%
  fill(term,.direction="up")


df3 <- tmp[1:dim(tmp)[1]/2,] %>% left_join(
  m_diff %>%
    mutate(
      pe = estimate,
      var = gsub(" ","",paste(feature,level,sep="")),
      group = feature,
      Type = "Difference in Marginal Means",
      match = BY,
      term = BY
    )%>%
    dplyr::select(group,pe,upper, lower, var ,term,Type),
  by=c("var"="var"))%>%
  fill(group,.direction="up") %>%
  fill(Type,.direction="up")%>%
  fill(term,.direction="up")


plot_df <- rbind(df1,df2,df3)%>%
   mutate(
     pe = ifelse(pe >10,NA,pe),
     lower = ifelse(lower >10,NA,lower),
     upper = ifelse(upper >10,NA,upper),
     Type = factor(Type,levels = c("AMCE","Marginal Means",
                                   "Difference in Marginal Means")),
     term = factor(term, levels=unique(term)[c(2,1,3)])
     )

vlines_df <- data.frame(Type = factor(na.omit(unique(plot_df$Type))),
                        z = c(0,.5,0))


p <- plot_df%>%
  filter(group %in% the_features)%>%
  ggplot(aes(x =pe, y=printvar,col=term, shape=term ))+
  facet_wrap(~Type, ncol=3L, drop=F, scale="free_x")+
  #scale_y_discrete(expand = c(0,0))+
  geom_point(position = ggstance::position_dodgev(height = -0.75), 
             size = 2, na.rm = TRUE)+
  geom_errorbarh(aes_string(xmin = "lower", xmax = "upper"),
    size = 0.5, height = 0, na.rm = TRUE,
    position = ggstance::position_dodgev(height = -0.75))+
  geom_vline(data=vlines_df,aes(xintercept=z),linetype=2,alpha=.5)+
  theme_bw()+
  xlab(interaction_lab)+
  ylab("")+
  ggplot2::theme(
        legend.title = element_blank(),
        legend.position = "bottom",
        panel.grid.minor = ggplot2::element_blank(),
        axis.title.x = element_text(vjust=-3),
        axis.text.y = element_text(hjust=0)

      )+
  scale_color_grey(start = 0.2, end = 0.7)
  p


}

table_fn <- function(p, the_cap="AMCE Estimates"){
  tab <- p$data%>%
  filter(!is.na(group))%>%
  mutate(
  printvar = factor(printvar,levels = printvar),
  pe = ifelse(pe > 100,"",sprintf("%.3f",pe)),
  se = ifelse(se > 100,"",sprintf("%.3f",se)),
  upper = ifelse(upper > 100,"",sprintf("%.3f",upper)),   
  lower = ifelse(lower > 100,"",sprintf("%.3f",lower))   
  )%>%
  arrange(desc(order))%>%
  dplyr::rename(" "=printvar, "AMCE"=pe,"SE"=se,"ll"=lower, "ul"=upper)%>%
  dplyr::select(" ",AMCE,SE,ll,ul)%>%
  kable(booktabs=T,
        caption = the_cap,
        align=c("l","c","c","c"))%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("Candidate Endorsements:",1,7)%>%
  kableExtra::group_rows("Candidate Experience:	",8,11)%>%
  kableExtra::group_rows("Candidate Ideology:",12,15)%>%
  kableExtra::group_rows("Candidate Age",16,21)%>%
  kableExtra::group_rows("Candiate Gender",22,23)%>%
  kableExtra::group_rows("Candidate Race",24,27)%>%
  kableExtra::group_rows("Candidate Occupation",28,32)
  return(tab)
}

format_ci_fn <- function(est){
  paste("[",sprintf("%.2f",est[,"lower"]),", ", sprintf("%.2f",est[,"upper"]),"]",sep="")
}

table_int_fn <- function(p, the_cap){
  
	amce_df_l <- p$data %>% filter(Type == "AMCE") %>% 
	  filter(term == "Low Trust") %>%
	  filter(!grepl(":",printvar))
	amce_df_h <- p$data %>% filter(Type == "AMCE") %>% 
	  filter(term == "High Trust")%>%
	  filter(!grepl(":",printvar))
	
	mm_df_l <- p$data %>% filter(Type == "Marginal Means") %>% 
	  filter(term == "Low Trust")%>%
	  filter(!grepl(":",printvar))
	mm_df_h <- p$data %>% filter(Type == "Marginal Means") %>% 
	  filter(term == "High Trust")%>%
	  filter(!grepl(":",printvar))
	
	mm_diff_df <- p$data %>% filter(Type == "Difference in Marginal Means")%>%
	  filter(!grepl(":",printvar))%>%
	  unique()
	
	tab <-matrix(NA, nrow = 2*dim(amce_df_l),ncol=6)
	est_seq <- seq(1,dim(tab)[1], by=2)
	ci_seq <- seq(2,dim(tab)[1], by=2)
	  
	tab[est_seq,1] <- as.character(amce_df_l$printvar)
	tab[ci_seq,1] <- ""
	
	tab[est_seq,2] <- ifelse(is.na(amce_df_l$pe), "",sprintf("%.3f",amce_df_l$pe))
	tab[ci_seq,2] <- ifelse(is.na(amce_df_l$pe),"", format_ci_fn(amce_df_l))
	tab[est_seq,3] <- ifelse(is.na(amce_df_h$pe), "",sprintf("%.3f",amce_df_h$pe))
	tab[ci_seq,3] <- ifelse(is.na(amce_df_h$pe),"", format_ci_fn(amce_df_h))
	
	
	tab[est_seq,4] <- ifelse(is.na(mm_df_l$pe), "",sprintf("%.3f",mm_df_l$pe))
	tab[ci_seq,4] <- ifelse(is.na(mm_df_l$pe), "",format_ci_fn(mm_df_l))
	tab[est_seq,5] <- ifelse(is.na(mm_df_h$pe), "",sprintf("%.3f",mm_df_h$pe))
	tab[ci_seq,5] <- ifelse(is.na(mm_df_h$pe), "",format_ci_fn(mm_df_h))
	
	tab[est_seq,6] <- ifelse(is.na(mm_diff_df$pe), "",sprintf("%.3f",mm_diff_df$pe))
	tab[ci_seq,6] <- ifelse(is.na(mm_diff_df$pe),"", format_ci_fn(mm_diff_df))
	colnames(tab) <- c(" ", "Low Trust", "High Trust","Low Trust", "High Trust", "LowTrust-High Trust")
	the_tab <- tab %>%
	  kable(booktabs = TRUE, 
          caption = the_cap, 
          align = c("l",rep("c",5)),
	          )%>%
	  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
	  add_header_above(c(" " = 1, "AMCE" = 2, "Marginal Means" = 2, "Difference in MM" = 1))%>%
	  kableExtra::group_rows("Candidate Endorsements:",1,14)%>%
	  kableExtra::group_rows("Candidate Experience:	",15,22)%>%
	  kableExtra::group_rows("Candidate Ideology:",23,30)
	return(the_tab)
}
```



# Main Results

## Table 1 MTurk Sample

```{r tab1 , results="asis"}
desc_stats <- c("female01","male01","resp_age","race_wht","race_blk",
                "race_asn","race_lat","race_haw","race_amin","race_oth",
                "pid_dem_all","pid_rep_all","prim01")
desc_stats_names <- c("Female", "Male", "Age", "White", "African American", 
                      "Asian American", "Latinx", "Hawaiian/Pacific Islander", 
                      "American Indian", "Other Race", "Democrat", "Republican", 
                      "Voted in Primary")
desc_stats_levels <- c(desc_stats_names, "All Respondents","Total Choices")
tab1 <- rbind(
  df_mt%>%
  summarise_at(vars(desc_stats),
               .funs=list(
                 Mean=function(x){mean(x, na.rm=T)},
                 N=function(x){sum(x>=1)})

  )%>%
  gather()%>%
  mutate(
    stat= str_replace(key,"^.*_",""),
    Variable = factor(rep(desc_stats_names,2),
                      levels = desc_stats_levels
                      )
  )%>%
  dplyr:::select(-key)%>%
  spread(stat,value)%>%
  dplyr:::select(Variable, N, Mean)%>%
    mutate(
      Mean = sprintf(Mean,fmt = '%#.2f')
    ),
  c("All Respondents",1195, "---"),
  c("Total Choices",1195, "---"))



kable(tab1, 
      caption = "MTurk Sample",
      booktabs=T,
      align = "lcc",
      digits = 2)%>%
  kable_styling()%>%
  row_spec(13,hline_after = T)

```

\setcounter{table}{2}

## Figure 1: Proportion of ANES Survey Respondents Indicating Trust in the FederalGovernment, 1964-2016

```{r figure1, fig.cap="Proportion of ANES Survey Respondents Indicating Trust in the FederalGovernment, 1964-2016"}

nes %>%
  dplyr::group_by(Year)%>%
  dplyr::summarise(
    Trust = mean(trust >2, na.rm=T)
  )%>%
  ggplot(aes(Year, Trust))+
  geom_point()+
  geom_line()+
  ylim(0,1)+
  scale_x_continuous(breaks = seq(1964,2016,by=4))+
  labs(
    x = "Year",
    y = "Proportion Indicating Trust in Government"
  )+
  theme_bw()
```


## Text: Average levels of trust by partisanship

> Democratic respondents indeed tend to have a slightly higher composite trust score ($\mu_{Dem} = 2.90$) than Republican respondents ($\mu_{Rep} = 2.73$).



```{r text1}
mean(df_mt$trust_scale[df_mt$pid_dem_all==1], na.rm=T)
mean(df_mt$trust_scale[df_mt$pid_rep_all==1], na.rm=T)
t.test(trust_scale ~ pid_dem_all, df_mt)
```


## Figure 2:  Distribution of Trust Among Democrats and Republicans

```{r figure2, fig.cap="Distribution of Trust Among Democrats and Republicans"}

p2_dem <- df_mt %>%
  filter(pid_dem_all==1)%>%
  ggplot( aes(trust_scale)) + 
       geom_bar(aes(y = (..count..)/sum(..count..))) +
       ggtitle("Distribution of Trust Among Democrats") +
       xlab("Trust") +
       ylab("Proportion") +
       theme_bw() +
       theme(plot.title = element_text(hjust = 0.5), panel.border =    
               element_blank(),
               panel.grid.major = element_blank(),
               panel.grid.minor = element_blank(), axis.line =       
                                  element_line(colour = "black"))
p2_rep <- df_mt %>%
  filter(pid_rep_all==1)%>%
  ggplot( aes(trust_scale)) + 
       geom_bar(aes(y = (..count..)/sum(..count..))) +
       ggtitle("Distribution of Trust Among Republicans") +
       xlab("Trust") +
       ylab("Proportion") +
       theme_bw() +
       theme(plot.title = element_text(hjust = 0.5), panel.border =    
               element_blank(),
               panel.grid.major = element_blank(),
               panel.grid.minor = element_blank(), axis.line =       
                                  element_line(colour = "black"))+
  ylim(0,.15)

ggarrange(p2_dem,p2_rep)

```


## Figure 3:  AMCE Estimates for Democratic and Republican Samples

```{r figure3, fig.width=12, fig.height=8, fig.cap="AMCE Estimates for Democratic and Republican Samples"}
the_model<- profile_chosen ~  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` + `Candidate Race` +
  `Candidate Occupation`

m1_d <- cjoint::amce(the_model , 
                     data = dem_df, 
                     cluster = T, 
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)




p1_d <- plot_fn(m1_d, # binary DV, no interactions
                plot.display = "unconditional",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = dem_levels,
                main = "AMCEs for Democratic Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  theme(
    axis.text.y = element_text(hjust=0)
  )+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")

m1_r <- cjoint::amce(the_model, 
                     data = rep_df, 
                     cluster = TRUE, 
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)

p1_r <- plot_fn(m1_r, # binary DV, no interactions
                plot.display = "unconditional",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = rep_levels,
                main = "AMCEs for Republican Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  theme(
    axis.text.y = element_text(hjust=0)
  )+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")


p1_d+p1_r


```



## Figure 4:  Democratic Support for Party Outsiders by Level of Trust

```{r figure4, fig.cap = "Democratic Support for Party Outsiders by Level of Trust"}
the_trust_model<- profile_chosen ~  lowtrustf*(`Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` + `Candidate Race` +
  `Candidate Occupation`)

m2_d <- cjoint::amce(the_trust_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)



p2_d <- plot_interaction_fn(dem_df,
                    m2_d,
                    the_model,
                    int = ~lowtrustf)

p2_d
```



## Figure 5: Republican Support for Party Outsiders by Level of Trust

```{r figure5, fig.cap="Republican Support for Party Outsiders by Level of Trust"}
m2_r <- cjoint::amce(the_trust_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)




p2_r <-plot_interaction_fn(rep_df,
                    m2_r,
                    the_model,
                    int = ~lowtrustf)

p2_r

```

## Text: Robustness checks in Footnote 7

>As a robustness check, we tested whether adding a “medium trust” categorization (thus breaking our sample into low-, medium-, and high-trust respondents) changes our results, but the differences between low and high-trust respondents were very similar to these main results.

```{r text2, width=10}

# Code <25th percentile as Low trust, 25th-75th as Medium and >75th as High
dem_df$trust_3cat <- cut(dem_df$trust_scale,
                         breaks = quantile(dem_df$trust_scale,probs=c(0,1/4,3/4,1)),
                         labels = c("Low","Medium","High"),include.lowest = T)
rep_df$trust_3cat <- cut(rep_df$trust_scale,breaks =
                           quantile(rep_df$trust_scale,probs=c(0,1/4,3/4,1)),
                         labels = c("Low","Medium","High"),include.lowest = T)

# 3 Trust Category Model
the_trust3cat_model<- profile_chosen ~  trust_3cat*(
  `Candidate Endorsements` + `Candidate Experience` + `Candidate Ideology` +  
    `Candidate Age` + `Candidate Gender` + `Candidate Race` + `Candidate Occupation`)

# Estimate AMCEs for 3 Trust Category Model For Democrats
m2_d_rob <- cjoint::amce(the_trust3cat_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "trust_3cat",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

# Plot AMCE for 3 Trust Category Model For Democrats
plot_fn(m2_d_rob,
        plot.display = "interaction",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = dem_levels,
                main = "AMCEs for Democratic Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")

# Estimate AMCEs for 3 Trust Category Model For Republicans
m2_r_rob <- cjoint::amce(the_trust3cat_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "trust_3cat",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)

# Plot AMCE for 3 Trust Category Model For Republicans
plot_fn(m2_r_rob,
        plot.display = "interaction",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = dem_levels,
                main = "AMCEs for Republican Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")
```

## Text: F-Tests of Interactions

>We conducted an F-test which determined that the overall relationship between composite trust score levels and endorsements is statistically significant (p <.0001).

> For Republicans, the only statistically significant overall interactions according to our F-tests were for the trust in party leader/endorsements and the trust in Trump/endorsements relationships.

```{r text3}
# Survey design
dem.design <- svydesign(ids = dem_df[["resp_id"]],  data=dem_df) 
rep.design <- svydesign(ids = rep_df[["resp_id"]],  data=rep_df)



############################################
## F-Tests for Democratic Respondents
###########################################

# Fit Linear Models for Testing
m2_d_t <- survey::svyglm(profile_chosen ~ lowtrustf*(
  cand_age + cand_gender + cand_race + cand_occup + cand_exp + cand_ideo + 
    cand_endorse + cand_endorse),
  design = dem.design
  )


# General Interaction
m2_d_t_gen <- linearHypothesis(m2_d_t,
                 names(m2_d_t$coefficients)[grep(":",
                                                 names(m2_d_t$coefficients))]
                 )
m2_d_t_gen
# Interaction with endorsements: 
m2_d_t_endorse<- linearHypothesis(m2_d_t,
                 names(m2_d_t$coefficients)[grep(":cand_endorse",
                                                 names(m2_d_t$coefficients))]
                 )
m2_d_t_endorse

# Interaction with experience: 
m2_d_t_exp<- linearHypothesis(m2_d_t,
                 names(m2_d_t$coefficients)[grep(":cand_exp",
                                                 names(m2_d_t$coefficients))]
                 )
m2_d_t_exp

# Interaction with ideology: 
m2_d_t_ideo<- linearHypothesis(m2_d_t,
                 names(m2_d_t$coefficients)[grep(":cand_ideo",
                                                 names(m2_d_t$coefficients))]
                 )
m2_d_t_ideo


############################################
## F-Tests for Repbulican Respondents
###########################################

# Fit Models

m2_r_t <- survey::svyglm(profile_chosen ~ lowtrustf*(
  cand_age + cand_gender + cand_race + cand_occup + cand_exp + cand_ideo + 
    cand_endorse + cand_endorse),
  design = rep.design
  )


# General interaction: Non-significant
m2_r_t_gen <- linearHypothesis(m2_r_t,
                 names(m2_r_t$coefficients)[grep(":",
                                                 names(m2_r_t$coefficients))]
                 )
m2_r_t_gen

# Interaction with endorsements:
m2_r_t_endorse<- linearHypothesis(m2_r_t,
                 names(m2_r_t$coefficients)[grep(":cand_endorse",
                                                 names(m2_r_t$coefficients))]
                 )
m2_r_t_endorse

# Interaction with experience: 
m2_r_t_exp<- linearHypothesis(m2_r_t,
                 names(m2_r_t$coefficients)[grep(":cand_exp",
                                                 names(m2_r_t$coefficients))]
                 )
m2_r_t_exp

# Interaction with ideology: 
m2_r_t_ideo<- linearHypothesis(m2_r_t,
                 names(m2_r_t$coefficients)[grep(":cand_ideo",
                                                 names(m2_r_t$coefficients))]
                 )
m2_r_t_ideo

```


## Table 3: Least and Most Preferred Candidates by Trust Level (Predicted Values)

```{r tab3, results="asis"}
fit_d <- lm(formula(m2_d_t),m2_d_t$data)


pred_dem_df <- data.frame(
  expand.grid(
    lowtrustf = c("High Trust","Low Trust"),
    `cand_age` = levels(fit_d$model$cand_age),
    `cand_gender` = levels(fit_d$model$cand_gender),
    `cand_race` = levels(fit_d$model$cand_race),
    `cand_occup` = levels(fit_d$model$cand_occup),
    `cand_exp` = levels(fit_d$model$cand_exp),
    `cand_ideo` = levels(fit_d$model$cand_ideo),
    `cand_endorse` = levels(fit_d$model$cand_endorse)
  )
)

pred_dem_df$fit <- predict(fit_d, newdata = pred_dem_df)
pred_dem_df <- pred_dem_df%>%
  arrange(fit)

fit_r <- lm(formula(m2_r_t),m2_r_t$data)


pred_rep_df <- data.frame(
  expand.grid(
    lowtrustf = c("High Trust","Low Trust"),
    `cand_age` = levels(fit_r$model$cand_age),
    `cand_gender` = levels(fit_r$model$cand_gender),
    `cand_race` = levels(fit_r$model$cand_race),
    `cand_occup` = levels(fit_r$model$cand_occup),
    `cand_exp` = levels(fit_r$model$cand_exp),
    `cand_ideo` = levels(fit_r$model$cand_ideo),
    `cand_endorse` = levels(fit_r$model$cand_endorse)
  )
)

pred_rep_df$fit <- predict(fit_r, newdata = pred_rep_df)
pred_rep_df <- pred_rep_df%>%
  arrange(fit)

pred_names <- c(
    'Age' = 'cand_age',
    'Gender' = 'cand_gender',
    'Race' = 'cand_race',
    'Occupation' = 'cand_occup',
    'Experience' = 'cand_exp',
    'Ideology' = 'cand_ideo',
    'Endorsement' = 'cand_endorse'
)

### Least preferred
least_pref_d_lt <- pred_dem_df%>%
  filter(lowtrustf == "Low Trust")%>%
  filter(fit==min(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = " ", value = "Least Preferred")

least_pref_d_ht <- pred_dem_df%>%
  filter(lowtrustf == "High Trust")%>%
  filter(fit==min(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = " ", value = "Least Preferred")

### Most Preferred

most_pref_d_lt <- pred_dem_df%>%
  filter(lowtrustf == "Low Trust")%>%
  filter(fit==max(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Most Preferred")

most_pref_d_ht <- pred_dem_df%>%
  filter(lowtrustf == "High Trust")%>%
  filter(fit==max(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Most Preferred")

### Least preferred
least_pref_r_lt <- pred_rep_df%>%
  filter(lowtrustf == "Low Trust")%>%
  filter(fit==min(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Least Preferred")

least_pref_r_ht <- pred_rep_df%>%
  filter(lowtrustf == "High Trust")%>%
  filter(fit==min(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Least Preferred")

### Most Preferred

most_pref_r_lt <- pred_rep_df%>%
  filter(lowtrustf == "Low Trust")%>%
  filter(fit==max(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Most Preferred")

most_pref_r_ht <- pred_rep_df%>%
  filter(lowtrustf == "High Trust")%>%
  filter(fit==max(fit,na.rm=T))%>%
  dplyr::select(starts_with("cand_"))%>%
  dplyr::rename(
    pred_names
  )%>%
  gather(key = "", value = "Most Preferred")

tab3 <- cbind(
  Trust = c(rep("Low Trust",7), rep("High Trust",7)),
  rbind(least_pref_d_lt,least_pref_d_ht),
  `Most Preferred` =c(most_pref_d_lt$`Most Preferred`,most_pref_d_ht$`Most Preferred`),
  `Least Preferred` =c(least_pref_r_lt$`Least Preferred`,least_pref_r_ht$`Least Preferred`),
  `Most Preferred` =c(most_pref_r_lt$`Most Preferred`,most_pref_r_ht$`Most Preferred`)
)
colnames(tab3)[1:2] <- " "
kable(tab3,
      booktabs=T,
      caption = "Least and Most Preferred Candidates by Trust Level (Predicted Values)"
        )%>%
  kable_styling()%>%
  add_header_above(c(" " = 2, "Democrats" = 2, "Republicans" = 2))%>%
  collapse_rows(columns = 1, latex_hline = "major", valign = "middle")


```

## Table 4: Qualtrics Sample

```{r tab4 , results="asis"}
desc_stats_q <- c("female01","male01","resp_age","race_wht","race_blk",
                "race_asn","race_lat","race_haw","race_amin","race_oth","prim01")
desc_stats_names_q <- c("Female", "Male", "Age", "White", "African American", 
                      "Asian American", "Latinx", "Hawaiian/Pacific Islander", 
                      "American Indian", "Other Race",
                      "Voted in 2018 or 2020 Primary")
desc_stats_levels_q <- c(desc_stats_names_q, "Total Respondents")


tab4 <- cbind(rbind(
  dem_df_q%>%
  summarise_at(vars(desc_stats_q),
               .funs=list(
                 Mean=function(x){mean(x, na.rm=T)},
                 N=function(x){sum(x>=1,na.rm=T)})

  )%>%
  gather()%>%
  mutate(
    stat= str_replace(key,"^.*_",""),
    Variable = factor(rep(desc_stats_names_q,2),
                      levels = desc_stats_levels_q
                      )
  )%>%
  dplyr:::select(-key)%>%
  spread(stat,value)%>%
  dplyr:::select(Variable, N, Mean)%>%
    mutate(
      Mean = sprintf(Mean,fmt = '%#.2f')
    ),
  c("Total Respondents",525, "--")),
  rbind(
  rep_df_q%>%
  summarise_at(vars(desc_stats_q),
               .funs=list(
                 Mean=function(x){mean(x, na.rm=T)},
                 N=function(x){sum(x>=1,na.rm=T)})

  )%>%
  gather()%>%
  mutate(
    stat= str_replace(key,"^.*_",""),
    Variable = factor(rep(desc_stats_names_q,2),
                      levels = desc_stats_levels_q
                      )
  )%>%
  dplyr:::select(-key)%>%
  spread(stat,value)%>%
  dplyr:::select(N, Mean)%>%
    mutate(
      Mean = sprintf(Mean,fmt = '%#.2f')
    ),
  c(525, "--"))
)



kable(tab4, 
      caption = "Qualtrics Sample",
      booktabs=T,
      align = "lcccc",
      digits = 2)%>%
  kable_styling()%>%
  add_header_above(c(" " = 1, "Democrats" = 2, "Republicans" = 2))%>%
  row_spec(11,hline_after = T)

```


## Figure 6: Democratic Support for Party Insider (Qualtrics Sample)

```{r figure6, fig.cap="Democratic Support for Party Insider (Qualtrics Sample)"}


ate_d <- lm_robust(insider_d ~ treat_dem_cand, dem_df_q)
cate_d_l <- lm_robust(insider_d ~ treat_dem_cand, dem_df_q, subset = lowtrustf == "Low Trust")
cate_d_h <- lm_robust(insider_d ~ treat_dem_cand, dem_df_q, subset = lowtrustf == "High Trust")

cate_d_party_l <- lm_robust(insider_d ~ treat_dem_cand, dem_df_q, subset = lowtrustpartyf == "Low Trust")
cate_d_party_h <- lm_robust(insider_d ~ treat_dem_cand, dem_df_q, subset = lowtrustpartyf == "High Trust")



fig6_df <- rbind(
  cbind(tidy(ate_d), Estimate = "Overall", 
        Estimand = "ATE", Trust = "General"),
  cbind(tidy(cate_d_l), Estimate = "Low Trust", 
        Estimand = "CATE", Trust = "General"),
  cbind(tidy(cate_d_h), Estimate = "High Trust", 
        Estimand = "CATE", Trust = "General"),
  cbind(tidy(ate_d), Estimate = "Overall", 
        Estimand = "ATE", Trust = "Democratic Party"),
  cbind(tidy(cate_d_party_l), Estimate = "Low Trust", 
        Estimand = "CATE", Trust = "Democratic Party"),
  cbind(tidy(cate_d_party_h), Estimate = "High Trust", 
        Estimand = "CATE", Trust = "Democratic Party")
)%>%
  filter(term != "(Intercept)")%>%
  mutate(
    Treatment = factor(gsub("treat_dem_cand","", term),
                       levels = rev(c("Endorsement Only","Experience Only", 
                                  "Endorsement and Experience"))),
    Estimate = factor(Estimate, levels = rev(unique(Estimate))),
    Trust = factor(Trust, levels = c("General", "Democratic Party"))
  )

fig6_df %>%
  ggplot(aes(Treatment, estimate, 
             col=Estimate,
             shape = Estimate
         ))+
  geom_point(position = position_dodge(width =.5))+
  geom_linerange(aes(ymin=conf.low, ymax = conf.high),
    position = position_dodge(width =c(.5)))+
  geom_hline(yintercept = 0,size = 0.5, colour = "black", 
                     linetype = "dotted")+
  theme_bw()+
  theme(
    panel.grid.minor = ggplot2::element_blank()
  )+
  scale_color_grey(start = 0.7, end = 0.2)+
  coord_flip()+
  facet_grid(~Trust)+
  guides(color = guide_legend(reverse = TRUE),
         shape = guide_legend(reverse = T)
         )+
  labs(
    y = "Treatment Effect on Democrats Preference for Insider Candidate",
    x = ""
  )
```




## Republican Support for Party Insider (Qualtrics Sample)


```{r figure7, fig.cap="Republican Support for Party Insider (Qualtrics Sample)"}

# Releveant Differences



# ATE endorsement
ate_end_r <- difference_in_means(insider_r ~ treat_endorsement, rep_df_q )
# CATE endorsement
cate_end_r_l <- difference_in_means(insider_r ~ treat_endorsement, 
                                  rep_df_q, subset = lowtrustf == "Low Trust" )
cate_end_r_h <-difference_in_means(insider_r ~ treat_endorsement, 
                    rep_df_q, subset = lowtrustf == "High Trust" )
cate_end_r_party_l <- difference_in_means(insider_r ~ treat_endorsement, 
                                  rep_df_q, subset = lowtrustpartyf == "Low Trust" )

cate_end_r_party_h <- difference_in_means(insider_r ~ treat_endorsement, 
                    rep_df_q, subset = lowtrustpartyf == "High Trust" )  

cate_end_r_pres_l <- difference_in_means(insider_r ~ treat_endorsement, 
                                  rep_df_q, subset = lowtrustpresf == "Low Trust" )

cate_end_r_pres_h <- difference_in_means(insider_r ~ treat_endorsement, 
                    rep_df_q, subset = lowtrustpresf == "High Trust" )                    

# Format for Plotting

fig7_df <- rbind(
  data.frame(tidy(ate_end_r), Treatment = "Endorsement",
             Estimate = "Overall", Estimand = "ATE", Trust = "General"),
  data.frame(tidy(cate_end_r_l), Treatment = "Endorsement", 
             Estimate = "Low Trust",Estimand = "CATE", Trust = "General"),
  data.frame(tidy(cate_end_r_h), Treatment = "Endorsement", 
             Estimate = "High Trust", Estimand = "CATE", Trust = "General"),
    data.frame(tidy(ate_end_r), Treatment = "Endorsement",
             Estimate = "Overall", Estimand = "ATE", Trust = "Republican Party"),
  data.frame(tidy(cate_end_r_party_l), Treatment = "Endorsement", 
             Estimate = "Low Trust",Estimand = "CATE",Trust = "Republican Party"),
  data.frame(tidy(cate_end_r_party_h), Treatment = "Endorsement", 
             Estimate = "High Trust", Estimand = "CATE",Trust = "Republican Party"),
  data.frame(tidy(ate_end_r), Treatment = "Endorsement",
             Estimate = "Overall", Estimand = "ATE", Trust = "President Trump"),
  data.frame(tidy(cate_end_r_pres_l), Treatment = "Endorsement", 
             Estimate = "Low Trust",Estimand = "CATE", Trust = "President Trump"),
  data.frame(tidy(cate_end_r_pres_h), Treatment = "Endorsement", 
             Estimate = "High Trust", Estimand = "CATE",Trust = "President Trump")
)%>%
  mutate(
    Estimate = factor(Estimate, levels = rev(unique(Estimate))),
    Trust = factor(Trust, levels = c("General", "Republican Party", "President Trump"))
  )

fig7_df %>%
  ggplot(aes(Estimate, estimate,col=Estimate))+
  geom_point()+
  geom_linerange(aes(ymin = conf.low, ymax = conf.high))+
  coord_flip()+
  geom_hline(yintercept = 0,size = 0.5, colour = "black", 
                     linetype = "dotted")+
  theme_bw()+
  labs(
    y = "Treatment Effect on Preference for Insider Candidate",
    x = ""
  )+
  facet_grid(~Trust)+
  guides(color="none")+
  theme(
        legend.title = element_blank(),
        legend.position = "bottom",
        panel.grid.minor = ggplot2::element_blank()
  )+
  scale_color_grey(start = 0.7, end = 0.2)
```



# Online Appendix

## Table A.1 AMCE Estimates for Democratic Respondents in Figure 3

```{r tabA1, results="asis"}
table_fn(p1_d,the_cap="AMCE Estimates for Democratic Respondents in Figure 3")

```

```{r}
write(table_fn(p1_d,the_cap="AMCE Estimates for Democratic Respondents in Figure 3"),
      file = "00_tables/tabA1.tex")
```


\clearpage

## Table A.2 AMCE Estimates for Republican Respondents in Figure 3

```{r tabA2, results="asis"}
table_fn(p1_r,the_cap="AMCE Estimates for Republican Respondents in Figure 3")
```


```{r}
write(table_fn(p1_r,the_cap="AMCE Estimates for Republican Respondents in Figure 3"),
      file = "00_tables/tabA2.tex")
```

\clearpage


## Table A.3 Democratic Support for Party Outsiders by Level of Trust from Figure 4

```{r tabA3, results="asis"}
table_int_fn(p2_d,the_cap="Democratic Support for Party Outsiders by Level of Trust from Figure 4")
```

```{r}
write(
  table_int_fn(p2_d,the_cap="Democratic Support for Party Outsiders by Level of Trust from Figure 4"),
      file = "00_tables/tabA3.tex")
```


\clearpage


## Table A.4 AMCE Estimates for Republican Respondents in Figure 4

```{r tabA4, results="asis"}
table_int_fn(p2_r,the_cap="Republican Support for Party Outsiders by Level of Trust from Figure 4")
```

```{r}
write(
table_int_fn(p2_r,the_cap="Republican Support for Party Outsiders by Level of Trust from Figure 4"),
      file = "00_tables/tabA4.tex")
```


\clearpage

## Table A.5 Treatment Effect on Democrats Preference for Insider Candidate in Figure 5

```{r tabA5, results="asis"}
tab6_df <-fig6_df[-c(10:12),]
tabA5 <- tab6_df%>%
  transmute(
    ` ` = Treatment, 
    Estimate = estimate,
    SE = std.error,
    ll = conf.low,
    ul = conf.high
  )%>%
  kable(booktabs=T,
        caption = "Treatment Effect on Democrats Preference for Insider Candidate in Figure 5",
        align="lccc"
        )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("ATE:",1,3)%>%
  kableExtra::group_rows("General Trust: Low",4,6)%>%
  kableExtra::group_rows("General Trust: High",7,9)%>%
  kableExtra::group_rows("Party Trust: Low",10,12)%>%
  kableExtra::group_rows("Party Trust: High",13,15)

tabA5
  


```


```{r}
write(tabA5, file = "00_tables/tabA6.tex")
```


## Table A.6 Treatment Effect on Republicans Preference for Insider Candidate in Figure 6

```{r tabA6, results="asis"}
tab7_df <-fig7_df[-c(4,7),]
tabA6 <- tab7_df%>%
  transmute(
    ` ` = Estimate, 
    Estimate = estimate,
    SE = std.error,
    ll = conf.low,
    ul = conf.high
  )%>%
  kable(booktabs=T,
        caption = "Treatment Effect on Republican's Preference for Insider Candidate in Figure 6",
        align="lccc"
        )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("ATE:",1,1)%>%
  kableExtra::group_rows("General Trust:",2,3)%>%
  kableExtra::group_rows("Trust in Party:",4,5)%>%
  kableExtra::group_rows("Trust in President",6,7)

tabA6
  


```

```{r}
write(tabA6, file = "00_tables/tabA6.tex")
```



## Figure A.2:  Democratic Support for Party Outsiders by Level of Trust in Party Leaders

```{r figureA2, fig.cap =  "Democratic Support for Party Outsiders by Level of Trust in Party Leaders"}
# Define model
the_party_model<- profile_chosen ~  lowtrustpartyf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

# Fit model
m_party_d <- cjoint::amce(the_party_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustpartyf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

# Plot model
p_party_d <- plot_interaction_fn(dem_df,
                    m_party_d,
                    the_model,
                    int = ~lowtrustpartyf)

p_party_d

```

```{r tabApartyD, results="asis"}
table_int_fn(p_party_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in Party Leaders")
```

```{r}
write(
table_int_fn(p_party_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in Party Leaders"),
      file = "00_tables/tabApartyD.tex")
```

\clearpage


## Figure A.3:  Republican Support for Party Outsiders by Level of Trust in Party Leaders

```{r figureA3, fig.cap =  "Republican Support for Party Outsiders by Level of Trust in Party Leaders"}
# Fit model
m_party_r <- cjoint::amce(the_party_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustpartyf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_party_r <- plot_interaction_fn(rep_df,
                    m_party_r,
                    the_model,
                    int = ~lowtrustpartyf)

p_party_r
```


```{r tabApartyR, results="asis"}
table_int_fn(p_party_r,the_cap="Republican Support for Party Outsiders by Level of Trust in Party Leaders")
```

```{r}
write(
table_int_fn(p_party_r,the_cap="Republican Support for Party Outsiders by Level of Trust in Party Leaders"),
      file = "00_tables/tabApartyR.tex")
```

\clearpage

## Figure A.4:  Democratic Support for Party Outsiders by Level of Trust in Congress

```{r figureA4, fig.cap =  "Democratic Support for Party Outsiders by Level of Trust in Congress"}

the_con_model<- profile_chosen ~  lowtrustconf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

m_con_d <- cjoint::amce(the_con_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustconf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

p_con_d <- plot_interaction_fn(dem_df,
                    m_con_d,
                    the_model,
                    int = ~lowtrustconf)

p_con_d
```

```{r tabAconD, results="asis"}
table_int_fn(p_con_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in Congress")
```

```{r}
write(
table_int_fn(p_con_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in Congress"),
      file = "00_tables/tabAconD.tex")
```

\clearpage

## Figure A.5:  Republican Support for Party Outsiders by Level of Trust in Congress

```{r figureA5, fig.cap =  "Republican Support for Party Outsiders by Level of Trust in Congress"}
# Fit model
m_con_r <- cjoint::amce(the_con_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustconf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_con_r <- plot_interaction_fn(rep_df,
                    m_con_r,
                    the_model,
                    int = ~lowtrustconf)

p_con_r
```

```{r tabAconR, results="asis"}
table_int_fn(p_con_r,the_cap="Democratic Support for Party Outsiders by Level of Trust in Congress")
```

```{r}
write(
table_int_fn(p_con_r,the_cap="Republican Support for Party Outsiders by Level of Trust in Congress"),
      file = "00_tables/tabAconR.tex")
```

\clearpage

## Figure A.6:  Democratic Support for Party Outsiders by Level of Trust in the Federal Government

```{r figureA6, fig.cap =  "Democratic Support for Party Outsiders by Level of Trust in the Federal Government"}

the_fed_model<- profile_chosen ~  lowtrustfedf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

m_fed_d <- cjoint::amce(the_fed_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustfedf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

p_fed_d <- plot_interaction_fn(dem_df,
                    m_fed_d,
                    the_model,
                    int = ~lowtrustfedf)

p_fed_d
```


```{r tabAfedD, results="asis"}
table_int_fn(p_fed_d, the_cap="Democratic Support for Party Outsiders by Level of Trust in the Federal Government")
```

```{r}
write(
table_int_fn(p_fed_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in the Federal Government"),
      file = "00_tables/tabAfedD.tex")
```

\clearpage

## Figure A.7:  Republican Support for Party Outsiders by Level of Trust in the Federal Government

```{r figureA7, fig.cap =  "Republican Support for Party Outsiders by Level of Trust in the Federal Government" }
# Fit model
m_fed_r <- cjoint::amce(the_fed_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustfedf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_fed_r <- plot_interaction_fn(rep_df,
                    m_fed_r,
                    the_model,
                    int = ~lowtrustfedf)

p_fed_r
```

```{r tabAfedR, results="asis"}
table_int_fn(p_fed_r, the_cap="Republican Support for Party Outsiders by Level of Trust in the Federal Government")
```

```{r}
write(
table_int_fn(p_fed_r,the_cap="Republican Support for Party Outsiders by Level of Trust in the Federal Government"),
      file = "00_tables/tabAfedR.tex")
```

\clearpage

## Figure A.8:  Democratic Support for Party Outsiders by Level of Trust in Media

```{r figureA8, fig.cap =  "Democratic Support for Party Outsiders by Level of Trust in Media"}

the_media_model<- profile_chosen ~  lowtrustmediaf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

m_media_d <- cjoint::amce(the_media_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustmediaf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

p_media_d <- plot_interaction_fn(dem_df,
                    m_media_d,
                    the_model,
                    int = ~lowtrustmediaf)

p_media_d
```


```{r tabAmediaD, results="asis"}
table_int_fn(p_media_d, the_cap="Democratic Support for Party Outsiders by Level of Trust in Media")
```

```{r}
write(
table_int_fn(p_media_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in Media"),
      file = "00_tables/tabAmediaD.tex")
```

\clearpage

## Figure A.9:  Republican Support for Party Outsiders by Level of Trust in Media

```{r figureA9, fig.cap = "Republican Support for Party Outsiders by Level of Trust in Media"}

# Fit model
m_media_r <- cjoint::amce(the_media_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustmediaf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_media_r <- plot_interaction_fn(rep_df,
                    m_media_r,
                    the_model,
                    int = ~lowtrustmediaf)

p_media_r
```

```{r tabAmediaR, results="asis"}
table_int_fn(p_media_r, the_cap="Reublican Support for Party Outsiders by Level of Trust in Media")
```

```{r}
write(
table_int_fn(p_media_r,the_cap="Republican Support for Party Outsiders by Level of Trust in Media"),
      file = "00_tables/tabAmediaR.tex")
```

\clearpage

## Figure A.10:  Democratic Support for Party Outsiders by Level of Trust in President Trump

```{r figureA10, fig.cap =  "Democratic Support for Party Outsiders by Level of Trust in President Trump"}

the_pres_model<- profile_chosen ~  lowtrustpresf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

m_pres_d <- cjoint::amce(the_pres_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustpresf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

p_pres_d <- plot_interaction_fn(dem_df,
                    m_pres_d,
                    the_model,
                    int = ~lowtrustpresf)

p_pres_d
```

```{r tabApresD, results="asis"}
table_int_fn(p_pres_d, the_cap="Democratic Support for Party Outsiders by Level of Trust in President Trump")
```

```{r}
write(
table_int_fn(p_pres_d,the_cap="Democratic Support for Party Outsiders by Level of Trust in President Trump"),
      file = "00_tables/tabApresD.tex")
```

\clearpage

## Figure A.11:  Republican Support for Party Outsiders by Level of Trust in President Trump

```{r figureA11, fig.cap =  "Republican Support for Party Outsiders by Level of Trust in President Trump"}
# Fit model
m_pres_r <- cjoint::amce(the_pres_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustpresf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_pres_r <- plot_interaction_fn(rep_df,
                    m_pres_r,
                    the_model,
                    int = ~lowtrustpresf)

p_pres_r
```


```{r tabApresR, results="asis"}
table_int_fn(p_pres_r, the_cap="Republican Support for Party Outsiders by Level of Trust in President Trump")
```

```{r}
write(
table_int_fn(p_pres_r,the_cap="Republican Support for Party Outsiders by Level of Trust in President Trump"),
      file = "00_tables/tabApresR.tex")
```

\clearpage

## Figure A.12:  Democratic Support for Party Outsiders Using Randomized Trust Indicators

```{r figureA12, fig.cap =  "Democratic Support for Party Outsiders Using Randomized Trust Indicators"}

the_wc_model<- profile_chosen ~  lowtrustwcf*(
  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` 
  + `Candidate Race` + `Candidate Occupation`)

m_wc_d <- cjoint::amce(the_wc_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "lowtrustwcf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)

p_wc_d <- plot_interaction_fn(dem_df,
                    m_wc_d,
                    the_model,
                    int = ~lowtrustwcf)

p_wc_d
```


```{r tabAwcD, results="asis"}
table_int_fn(p_wc_d, the_cap="Democratic Support for Party Outsiders Using Randomized Trust Indicators")
```

```{r}
write(
table_int_fn(p_wc_d,the_cap="Democratic Support for Party Outsiders Using Randomized Trust Indicators"),
      file = "00_tables/tabAwcD.tex")
```

\clearpage

## Figure A.13:  Republican Support for Party Outsiders Using Randomized Trust Indicators

```{r figureA13, fig.cap =  "Republican Support for Party Outsiders Using Randomized Trust Indicators"}
# Fit model
m_wc_r <- cjoint::amce(the_wc_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "lowtrustwcf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
# Plot model
p_wc_r <- plot_interaction_fn(rep_df,
                    m_wc_r,
                    the_model,
                    int = ~lowtrustwcf)

p_wc_r
```


```{r tabAwcR, results="asis"}
table_int_fn(p_wc_r, the_cap="Republican Support for Party Outsiders Using Randomized Trust Indicators")
```

```{r}
write(
table_int_fn(p_wc_r,the_cap="Republican Support for Party Outsiders Using Randomized Trust Indicators"),
      file = "00_tables/tabAwcR.tex")
```

\clearpage

## Figure A.14: Democratic Support by Competitiveness of the General Election

```{r figureA14, fig.cap = "Democratic Support by Competitiveness of the General Election"}
the_comp_model<- profile_chosen ~  general*(`Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` + `Candidate Race` +
  `Candidate Occupation`)

m3_d <- cjoint::amce(the_comp_model , 
                     data = dem_df, 
                     cluster = T,
                     respondent.varying = "general",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)
p6_d_df <- get_data_fn(m3_d,
                       group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation"))


p6_d_df %>%
  mutate(
    `General Election` = ifelse(grepl("Comp",facet),"Competitive","Safe")
  )%>%
  filter(facet!="Unconditional")%>%
  ggplot(aes(x=fct_reorder(printvar,order),y=pe,
        ymin=lower,ymax=upper,col=`General Election`,shape=`General Election`))+
  geom_pointrange(aes(ymin = lower, ymax = upper), 
                          position = position_dodge(width = 0.5))+
  ylim(-.35,.45)+
  geom_hline(yintercept = 0, size = 0.5, colour = "black", 
                     linetype = "dotted")+
  labs(
    y = "Change: Pr(Prefer Candidate)",
    x = "",
    shape="General Election",
    col="General Election"
  )+
  coord_flip()+
  theme_bw()+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(shape="none")


```

```{r tabAcompD}
comp_d_tab <- list(data = p6_d_df%>% filter(grepl("Comp",facet)))
table_fn(comp_d_tab,the_cap = "Democratic Support in Competitive General Elections")
```

```{r}
write(table_fn(comp_d_tab, the_cap = "Democratic Support in Competitive General Elections"),      
file = "00_tables/tabAcompD.tex")
```

\clearpage

```{r tabAsafeD}
safe_d_tab <- list(data = p6_d_df%>% filter(grepl("Safe",facet)))
table_fn(safe_d_tab,
         the_cap = "Democratic Support in Safe General Elections"
         )
```

```{r}
write(table_fn(safe_d_tab, the_cap = "Democratic Support in Safe General Elections"),      
file = "00_tables/tabAsafeD.tex")
```

\clearpage

## Figure A.15: Republican Support by Competitiveness of the General Election

```{r figureA15, fig.cap = "Republican Support by Competitiveness of the General Election"}


m3_r <- cjoint::amce(the_comp_model , 
                     data = rep_df, 
                     cluster = T,
                     respondent.varying = "general",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)
p6_r_df <- get_data_fn(m3_r,
                       group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation"))


p6_r_df %>%
  mutate(
    `General Election` = ifelse(grepl("Comp",facet),"Competitive","Safe")
  )%>%
  filter(facet!="Unconditional")%>%
  ggplot(aes(x=fct_reorder(printvar,order),y=pe,
        ymin=lower,ymax=upper,col=`General Election`,shape=`General Election`))+
  geom_pointrange(aes(ymin = lower, ymax = upper), 
                          position = position_dodge(width = 0.5))+
  ylim(-.35,.45)+
  geom_hline(yintercept = 0, size = 0.5, colour = "black", 
                     linetype = "dotted")+
  labs(
    y = "Change: Pr(Prefer Candidate)",
    x = "",
    shape="General Election",
    col="General Election"
  )+
  coord_flip()+
  theme_bw()+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(shape="none")


```

```{r tabAcompR}
comp_r_tab <- list(data = p6_r_df%>% filter(grepl("Comp",facet)))
table_fn(comp_r_tab,the_cap = "Republican Support in Competitive General Elections")
```

```{r}
write(table_fn(comp_r_tab, the_cap = "Republican Support in Competitive General Elections"),      
file = "00_tables/tabAcompR.tex")
```

\clearpage

```{r tabAsafeR}
safe_r_tab <- list(data = p6_r_df%>% filter(grepl("Safe",facet)))
table_fn(safe_r_tab,
         the_cap = "Republican Support in Safe General Elections"
         )
```

```{r}
write(table_fn(safe_r_tab, the_cap = "Republican Support in Safe General Elections"),      
file = "00_tables/tabAsafeR.tex")
```

\clearpage

## Figure A.16 Candidate Endorsements Conditional on Candidate Ideology


```{r figA16, fig.cap="Candidate Endorsements Conditional on Candidate Ideology", fig.height=6}
# Pair indicators
dem_df$pairid <- paste(dem_df$choice_no,dem_df$resp_id,sep="_")
rep_df$pairid <- paste(rep_df$choice_no,rep_df$resp_id,sep="_")

# Fit Causal ANOVA

fit_dem_end <- CausalANOVA(formula= profile_chosen ~ `Candidate Endorsements` + `Candidate Experience` + 
    `Candidate Ideology` + `Candidate Age` + `Candidate Gender` + 
    `Candidate Race` + `Candidate Occupation`,
                    int2.formula = ~ `Candidate Endorsements`:`Candidate Ideology`,
                    data=dem_df, pair.id=dem_df$pairid,diff=TRUE,
                    ord.fac = c(T,T,T,T,F,F,F),
                    cluster=dem_df$resp_id, nway=2)

fit_rep_end <- CausalANOVA(formula= profile_chosen ~ `Candidate Endorsements` + `Candidate Experience` + 
    `Candidate Ideology` + `Candidate Age` + `Candidate Gender` + 
    `Candidate Race` + `Candidate Occupation`,
                    int2.formula = ~ `Candidate Endorsements`:`Candidate Ideology`,
                    data=rep_df, pair.id=rep_df$pairid,diff=TRUE,
                    ord.fac = c(T,T,T,T,F,F,F),
                    cluster=rep_df$resp_id, nway=2)

# Format Conditional Effects

ce_dem_end <- ConditionalEffect(fit_dem_end, treat.fac="`Candidate Endorsements`", cond.fac="`Candidate Ideology`",base.ind = 1)

ce_rep_end <- ConditionalEffect(fit_rep_end, treat.fac="`Candidate Endorsements`", cond.fac="`Candidate Ideology`",base.ind = 1)

ce_dem_end_df  <- do.call(rbind,ce_dem_end$ConditionalEffects)
ce_rep_end_df  <- do.call(rbind,ce_rep_end$ConditionalEffects)

colnames(ce_dem_end_df) <- c("conditionaleffect", "sd","lwr","upr")
colnames(ce_rep_end_df) <- c("conditionaleffect", "sd","lwr","upr")

ce_dem_end_df <- cbind("Candidate Endorsements"=rownames(ce_dem_end_df),
              data.frame(ce_dem_end_df), 
              "Candidate Ideology"= paste("Candidate Ideology =",
                                          c(rep("6",7),
                                            rep("7",7),
                                            rep("8",7),
                                            rep("9",7))
                                          )
              )

ce_rep_end_df <- cbind("Candidate Endorsements"=rownames(ce_rep_end_df),
              data.frame(ce_rep_end_df), 
              "Candidate Ideology"= paste("Candidate Ideology =",
                                          c(rep("6",7),
                                            rep("7",7),
                                            rep("8",7),
                                            rep("9",7))
                                          )
              )

# Plot Results

p_ce_dem_end <- ce_dem_end_df %>%
  mutate(
    `Candidate Endorsements` = factor(`Candidate Endorsements`, levels = rev(levels(dem_df$cand_endorse)))
  )%>%
  ggplot(aes(`Candidate Endorsements`, conditionaleffect,
             shape = `Candidate Ideology`,
             col = `Candidate Ideology`))+
  geom_point(position = position_dodge(width = .5))+
  geom_linerange(aes(ymin=lwr, ymax=upr),
                 position = position_dodge(width = .5))+
  geom_hline(aes(yintercept=0),linetype=2,alpha=.5)+
  coord_flip()+
  facet_wrap(~`Candidate Ideology`,ncol=1)+
  labs(
    y="Conditional Effects",
    x ="",
    title="Democrats"
  )+
  theme_bw()+
  theme(
        panel.grid.minor = ggplot2::element_blank(),
      )+
  scale_color_grey(start = 0.2, end = 0.7)+
  guides(shape="none",col="none")

p_ce_rep_end <- ce_rep_end_df %>%
  mutate(
    `Candidate Endorsements` = factor(`Candidate Endorsements`, levels = rev(levels(rep_df$cand_endorse)))
  )%>%
  ggplot(aes(`Candidate Endorsements`, conditionaleffect,
             shape = `Candidate Ideology`,
             col = `Candidate Ideology`))+
  geom_point(position = position_dodge(width = .5))+
  geom_linerange(aes(ymin=lwr, ymax=upr),
                 position = position_dodge(width = .5))+
  geom_hline(aes(yintercept=0),linetype=2,alpha=.5)+
  coord_flip()+
  facet_wrap(~`Candidate Ideology`,ncol=1)+
  labs(
    y="Conditional Effects",
    x ="",
    title="Republicans"
  )+
  theme_bw()+
  theme(
        panel.grid.minor = ggplot2::element_blank(),
      )+
  scale_color_grey(start = 0.2, end = 0.7)+
  guides(shape="none",col="none")

p_ce_dem_end + p_ce_rep_end

```

```{r tabAceEndD, results="asis"}
tabAceEndD <- ce_dem_end_df %>%
  filter(`Candidate Endorsements` != "NoEndorsements")%>%
  transmute(
    " " = `Candidate Endorsements`,
    "Conditional Effect" = conditionaleffect,
    SE = sd,
    ll = lwr,
    ul = upr
  )%>%
  kable(
    booktabs=T,
    caption = "Candidate Endorsements Conditional on Candidate Ideology for Democrats",
    align = "lccc"
  )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("Ideology = 6",1,6)%>%
  kableExtra::group_rows("Ideology = 7",7,12)%>%
  kableExtra::group_rows("Ideology = 8",13,18)%>%
  kableExtra::group_rows("Ideology = 9",19,24)

tabAceEndD
  
```

```{r}
write(tabAceEndD, file ="00_tables/tabAceEndD.tex")
```



```{r tabAceEndR, results="asis"}
tabAceEndR <- ce_rep_end_df %>%
  filter(`Candidate Endorsements` != "NoEndorsements")%>%
  transmute(
    " " = `Candidate Endorsements`,
    "Conditional Effect" = conditionaleffect,
    SE = sd,
    ll = lwr,
    ul = upr
  )%>%
  kable(
    booktabs=T,
    caption = "Candidate Endorsements Conditional on Candidate Ideology for Republicans",
    align = "lccc"
  )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("Ideology = 6",1,6)%>%
  kableExtra::group_rows("Ideology = 7",7,12)%>%
  kableExtra::group_rows("Ideology = 8",13,18)%>%
  kableExtra::group_rows("Ideology = 9",19,24)

tabAceEndR  
```

```{r}
write(tabAceEndR, file ="00_tables/tabAceEndR.tex")
```

\clearpage

## Figure A.17 Candidate Experience Conditional on Candidate Ideology


```{r figA17, fig.cap="Candidate Experience Conditional on Candidate Ideology", fig.height=6}
# Fit Causal ANOVA
fit_dem_exp <- CausalANOVA(formula= profile_chosen ~ `Candidate Endorsements` + `Candidate Experience` + 
    `Candidate Ideology` + `Candidate Age` + `Candidate Gender` + 
    `Candidate Race` + `Candidate Occupation`,
                    int2.formula = ~ `Candidate Experience`:`Candidate Ideology`,
                    data=dem_df, pair.id=dem_df$pairid,diff=TRUE,
                    ord.fac = c(T,T,T,T,F,F,F),
                    cluster=dem_df$resp_id, nway=2)

fit_rep_exp <- CausalANOVA(formula= profile_chosen ~ `Candidate Endorsements` + `Candidate Experience` + 
    `Candidate Ideology` + `Candidate Age` + `Candidate Gender` + 
    `Candidate Race` + `Candidate Occupation`,
                    int2.formula = ~ `Candidate Experience`:`Candidate Ideology`,
                    data=rep_df, pair.id=rep_df$pairid,diff=TRUE,
                    ord.fac = c(T,T,T,T,F,F,F),
                    cluster=rep_df$resp_id, nway=2)

# Format Condtional Effects
ce_dem_exp <- ConditionalEffect(fit_dem_exp, treat.fac="`Candidate Experience`", cond.fac="`Candidate Ideology`",base.ind = 1)

ce_rep_exp <- ConditionalEffect(fit_rep_exp, treat.fac="`Candidate Experience`", cond.fac="`Candidate Ideology`",base.ind = 1)

ce_dem_exp_df  <- do.call(rbind,ce_dem_exp$ConditionalEffects)
ce_rep_exp_df  <- do.call(rbind,ce_rep_exp$ConditionalEffects)

colnames(ce_dem_exp_df) <- c("conditionaleffect", "sd","lwr","upr")
colnames(ce_rep_exp_df) <- c("conditionaleffect", "sd","lwr","upr")

ce_dem_exp_df <- cbind("Candidate Experience"=rownames(ce_dem_exp_df),
              data.frame(ce_dem_exp_df), 
              "Candidate Ideology"= paste("Candidate Ideology =",c(rep("6",4),
                                 rep("7",4),
                                 rep("8",4),
                                 rep("9",4))))

ce_rep_exp_df <- cbind("Candidate Experience"=rownames(ce_rep_exp_df),
              data.frame(ce_rep_exp_df), 
              "Candidate Ideology"= paste("Candidate Ideology =",c(rep("6",4),
                                 rep("7",4),
                                 rep("8",4),
                                 rep("9",4))))

# Plot Conditional Effects
p_ce_dem_exp <- ce_dem_exp_df %>%
  mutate(
    `Candidate Experience` = factor(`Candidate Experience`, levels = rev(levels(dem_df$cand_exp)))
  )%>%
  ggplot(aes(`Candidate Experience`, conditionaleffect,
             shape = `Candidate Ideology`,
             col = `Candidate Ideology`))+
  geom_point(position = position_dodge(width = .5))+
  geom_linerange(aes(ymin=lwr, ymax=upr),
                 position = position_dodge(width = .5))+
  geom_hline(aes(yintercept=0),linetype=2,alpha=.5)+
  coord_flip()+
  facet_wrap(~`Candidate Ideology`,ncol=1)+
  labs(
    y="Conditional Effects",
    x ="",
    title="Democrats"
  )+
  theme_bw()+
  theme(
        panel.grid.minor = ggplot2::element_blank(),
      )+
  scale_color_grey(start = 0.2, end = 0.7)+
  guides(shape="none",col="none")

p_ce_rep_exp <- ce_rep_exp_df %>%
  mutate(
    `Candidate Experience` = factor(`Candidate Experience`, levels = rev(levels(rep_df$cand_exp)))
  )%>%
  ggplot(aes(`Candidate Experience`, conditionaleffect,
             shape = `Candidate Ideology`,
             col = `Candidate Ideology`))+
  geom_point(position = position_dodge(width = .5))+
  geom_linerange(aes(ymin=lwr, ymax=upr),
                 position = position_dodge(width = .5))+
  geom_hline(aes(yintercept=0),linetype=2,alpha=.5)+
  coord_flip()+
  facet_wrap(~`Candidate Ideology`,ncol=1)+
  labs(
    y="Conditional Effects",
    x ="",
    title="Republicans"
  )+
  theme_bw()+
  theme(
        panel.grid.minor = ggplot2::element_blank(),
      )+
  scale_color_grey(start = 0.2, end = 0.7)+
  guides(shape="none",col="none")

p_ce_dem_exp + p_ce_rep_exp

```


```{r tabAceExpD, results="asis"}
tabAceExpD <- ce_dem_exp_df %>%
  filter(`Candidate Experience` != "None")%>%
  transmute(
    " " = `Candidate Experience`,
    "Conditional Effect" = conditionaleffect,
    SE = sd,
    ll = lwr,
    ul = upr
  )%>%
  kable(
    booktabs=T,
    caption = "Candidate Experience Conditional on Candidate Ideology for Democrats",
    align = "lccc"
  )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("Ideology = 6",1,3)%>%
  kableExtra::group_rows("Ideology = 7",4,6)%>%
  kableExtra::group_rows("Ideology = 8",7,9)%>%
  kableExtra::group_rows("Ideology = 9",10,12)

tabAceExpD
  
```

```{r}
write(tabAceExpD, file ="00_tables/tabAceExpD.tex")
```



```{r tabAceExpR, results="asis"}
tabAceExpR <- ce_rep_exp_df %>%
  filter(`Candidate Experience` != "None")%>%
  transmute(
    " " = `Candidate Experience`,
    "Conditional Effect" = conditionaleffect,
    SE = sd,
    ll = lwr,
    ul = upr
  )%>%
  kable(
    booktabs=T,
    caption = "Candidate Experience Conditional on Candidate Ideology for Republicans",
    align = "lccc"
  )%>%
  kable_styling(latex_options = c("HOLD_position",font_size=10)) %>%
  kableExtra::group_rows("Ideology = 6",1,3)%>%
  kableExtra::group_rows("Ideology = 7",4,6)%>%
  kableExtra::group_rows("Ideology = 8",7,9)%>%
  kableExtra::group_rows("Ideology = 9",10,12)

tabAceExpR  
```

```{r}
write(tabAceExpR, file ="00_tables/tabAceExpR.tex")
```

\clearpage

## Figure A.18:  AMCE Estimates for Democratic and Republican Samples Excluding Problematic Responses

```{r figA18, fig.width=12, fig.height=8, fig.cap="AMCE Estimates for Democratic and Republican Samples Excluding Problematic Responses"}
the_model<- profile_chosen ~  `Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` + `Candidate Race` +
  `Candidate Occupation`

m1_d_noprob <- cjoint::amce(the_model , 
                     data = dem_df[dem_df$redflag == 0, ], 
                     cluster = T, 
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)




p1_d_noprob <- plot_fn(m1_d_noprob, # binary DV, no interactions
                plot.display = "unconditional",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = dem_levels,
                main = "AMCEs for Democratic Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  theme(
    axis.text.y = element_text(hjust=0)
  )+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")

m1_r_noprob <- cjoint::amce(the_model, 
                     data = rep_df[rep_df$redflag == 0, ], 
                     cluster = TRUE, 
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)

p1_r_noprob <- plot_fn(m1_r_noprob, # binary DV, no interactions
                plot.display = "unconditional",
                xlab = "Change: Pr(Prefer Candidate)", 
                text.size = 7,
                level.names = rep_levels,
                main = "AMCEs for Republican Primary\nCandidate Profiles",
                ci = 0.95,
                breaks = c(-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3), 
                labels = c("-0.3", "-0.2", "-0.1", 
                           "0", "0.1", "0.2", "0.3"),
                group.order = c(
                  "Candidate Endorsements",
                  "Candidate Experience","Candidate Ideology",
                  "Candidate Age","Candidate Gender",
                  "Candidate Race", "Candidate Occupation")
     )+
  theme_bw()+
  theme(
    axis.text.y = element_text(hjust=0)
  )+
  aes(shape=group)+
  scale_shape_manual(values=c(1:6,8))+
  scale_color_grey(start = .1, end = .6)+
  guides(col="none",shape="none")


p1_d_noprob+p1_r_noprob


```

```{r tabA18, results="asis"}
table_fn(p1_d_noprob,the_cap="AMCE Estimates for Democratic Respondents in Figure 3 Excluding Problematic Responses ")

```

```{r}
write(table_fn(p1_d_noprob,the_cap="AMCE Estimates for Democratic Respondents in Figure 3 Excluding Problematic Responses"),
      file = "00_tables/tabA18noprob.tex")
```


## Figure A.19:  Democratic Support for Party Outsiders by Level of Trust Excluding Problematic Responses

```{r figA19, fig.cap = "Democratic Support for Party Outsiders by Level of Trust Excluding Problematic Responses"}
the_trust_model<- profile_chosen ~  lowtrustf*(`Candidate Endorsements` + `Candidate Experience` +
  `Candidate Ideology` +  `Candidate Age` + `Candidate Gender` + `Candidate Race` +
  `Candidate Occupation`)

m2_d_noprob <- cjoint::amce(the_trust_model , 
                     data = dem_df[dem_df$redflag == 0, ], 
                     cluster = T,
                     respondent.varying = "lowtrustf",
                     respondent.id = "resp_id", 
                     design = design_dem, 
                     baselines = baselines)



p2_d_noprob <- plot_interaction_fn(dem_df[dem_df$redflag == 0, ],
                    m2_d_noprob,
                    the_model,
                    int = ~lowtrustf)

p2_d_noprob
```


```{r tabA19, results="asis"}
table_int_fn(p2_d_noprob,the_cap="AMCE Estimates for Democratic Respondents in Figure 3 Excluding Problematic Responses ")

```

```{r}
write(table_int_fn(p2_d_noprob,the_cap="AMCE Estimates for Democratic Respondents in Figure 3 Excluding Problematic Responses"),
      file = "00_tables/tabA19noprob.tex")
```


## Figure A.20: Republican Support for Party Outsiders by Level of Trust Excluding Problematic Responses

```{r figA20, fig.cap="Republican Support for Party Outsiders by Level of Trust Excluding Problematic Responses"}
m2_r_noprob <- cjoint::amce(the_trust_model , 
                     data = rep_df[rep_df$redflag == 0,], 
                     cluster = T,
                     respondent.varying = "lowtrustf",
                     respondent.id = "resp_id", 
                     design = design_rep, 
                     baselines = baselines)




p2_r_noprob <-plot_interaction_fn(rep_df[rep_df$redflag == 0,],
                    m2_r_noprob,
                    the_model,
                    int = ~lowtrustf)

p2_r_noprob

```

```{r tabA20, results="asis"}
table_int_fn(p2_r_noprob,the_cap="AMCE Estimates for Republican Respondents in Figure 3 Excluding Problematic Responses ")

```

```{r}
write(table_int_fn(p2_r_noprob,the_cap="AMCE Estimates for Republican Respondents in Figure 3 Excluding Problematic Responses"),
      file = "00_tables/tabA20nobrob.tex")
```
